import {
  getInspectionTemplateMasterItemByPage,
  addInspectionTemplateMasterItem,
  updateInspectionTemplateMasterItem,
  delInspectionTemplateMasterItem,
  exportInspectionTemplateMasterItem,
  getInspectionTemplateMasterItemBySortId,
} from '@/services/quality/inspectionTemplateMasterItem';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, InputNumber, Select } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
const InspectionTemplateMasterItem: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const theid = props.theid;
  const [form] = Form.useForm();
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '自定义项目名称',
      dataIndex: 'name',
      width: 175,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '位置类型',
      dataIndex: 'position',
      width: 120,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '表头排序',
      dataIndex: 'sortId',
      width: 90,
      align: 'center',
      sorter: true,

      valueType: 'digit',
    },
    // {
    //   title: '填入值的类型',
    //   dataIndex: 'valueType',
    //   width: 130,
    //  align: 'center',sorter: true,
    //
    //   search: false,
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    //   search: false,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              customItemId: record.customItemId,
              inspectionTemplateId: record.inspectionTemplateId,
              memo: record.memo,
              name: record.name,
              position: record.position,
              sortId: record.sortId,
              valueType: record.valueType,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectionTemplateMasterItem({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.inspectionTemplateId = theid;
          console.log(res);
          const new_params = {
            inspectionTemplateId: res.inspectionTemplateId,
            sortId: res.sortId,
          };
          const new_result = await getInspectionTemplateMasterItemBySortId(new_params);
          if (new_result.data == null) {
            res.valueType = '文本';
            const result = await addInspectionTemplateMasterItem(res);
            if (result != null) {
              message.success('添加成功');
              setConfirmLoading(false);
              setModalVisit(false);
              actionRef.current!.reload();
            }
          } else {
            message.warning('自定义项排序重复');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.inspectionTemplateId = theid;
          res.valueType = '文本';
          console.log(res);
          const result = await updateInspectionTemplateMasterItem(res);
          if (result != null) {
            message.success('修改成功');
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current!.reload();
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="自定义项目查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.setFieldsValue({
                position: '表头',
              });
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportInspectionTemplateMasterItem({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `InspectionTemplateMasterItem.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, inspectionTemplateId: theid };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const result = await getInspectionTemplateMasterItemByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 900, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        destroyOnClose
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        width={600}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '150px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <input />
          </Form.Item>

          <Form.Item
            label="自定义项目名称"
            name="name"
            rules={[{ required: true, message: '请输入自定义项目名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="自定义项目位置类型"
            name="position"
            rules={[{ required: true, message: '请选择自定义项目位置类型!' }]}
          >
            <Select
              disabled
              placeholder="请选择自定义项目位置类型"
              // onChange={changeinspector}
              options={[
                { value: '表头', label: '表头' },
                { value: '页尾', label: '页尾' },
                { value: '边栏', label: '边栏' },
              ]}
            />
          </Form.Item>
          {/* <Form.Item
            label="输入值类型"
            name="valueType"
            rules={[{ required: true, message: '请选择输入值类型！' }]}
          >
            <Select
              placeholder="请选择输入值类型"
              options={[
                { value: '文本', label: '文本' },
                { value: '小数', label: '小数' },
                { value: '整数', label: '整数' },
                { value: '布尔型', label: '布尔型' },
                { value: '日期', label: '日期' },
              ]}
            />
          </Form.Item> */}
          <Form.Item
            label="项目排序"
            name="sortId"
            rules={[{ required: true, message: '请输入项目排序!' }]}
          >
            <InputNumber min={1} max={100} precision={0} style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default InspectionTemplateMasterItem;
